//
//  WBQRCodeCreatViewController.swift
//  weibo
//
//  Created by Felix on 16/11/9.
//  Copyright © 2016年 Felix. All rights reserved.
//

import UIKit

class WBQRCodeCreatViewController: UIViewController {

    @IBOutlet var codeImageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()

        creatQRCode()
    }
    func creatQRCode() ->  Void{
        //1.创建滤镜
        let filter =  CIFilter(name: "CIQRCodeGenerator")
        
        //2.还原默认设置
        filter?.setDefaults()
        
        //3.设置二维码值
        filter?.setValue("AdaLoveFelix".data(using: String.Encoding.utf8), forKey: "InputMessage")
        

        guard let outImage = filter?.outputImage else {
            return
        }
        //如果有值则拿到值生成一个高清图片并赋值
        codeImageView.image = createNonInterpolatedUIImageFormCIImage(image: outImage, size: 500)
    }

    /**
     生成高清二维码
     
     - parameter image: 需要生成原始图片
     - parameter size:  生成的二维码的宽高
     */
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
        let extent: CGRect = image.extent.integral
        let scale: CGFloat = min(size/extent.width, size/extent.height)
        
        // 1.创建bitmap;
        let width = extent.width * scale
        let height = extent.height * scale
        let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: extent)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: scale, y: scale);
        
        bitmapRef.draw(bitmapImage, in: extent)
        
        // 2.保存bitmap到图片
        let scaledImage: CGImage = bitmapRef.makeImage()!
        
        return UIImage(cgImage: scaledImage)
    }


}
